package de.ipk_gatersleben.bit.bi.edal.publication.metadata;

import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;

public class FileProgressMonitor {

	private JProgressBar fileProgressBar;
	private int max;

	/**
	 * Constructs a graphic object that shows progress, typically by filling in
	 * a rectangular bar as the process nears completion.
	 * 
	 * @param max
	 *            the upper bound of the range
	 */
	public FileProgressMonitor(JProgressBar fileProgressBar, int max) {
		this.max = max;
		this.fileProgressBar = fileProgressBar;

	}

	/**
	 * Indicate the progress of the operation being monitored. If the specified
	 * value is >= the maximum, the progress monitor is closed.
	 * 
	 * @param newValue
	 *            an int specifying the current value, between the maximum and
	 *            minimum specified for this component
	 */
	@SuppressWarnings("restriction")
	public void setProgress(final int newValue) {

		if (newValue >= max) {
			close();
		} else if (this.fileProgressBar != null) {
			try {

				if (sun.awt.AppContext.getAppContext() == null) {
					sun.awt.SunToolkit.createNewAppContext();
				}

				SwingUtilities.invokeAndWait(new Runnable() {
					public void run() {
						fileProgressBar.setValue((int) Math.ceil(100.0 / max
								* newValue));
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * Indicate that the operation is complete. This happens automatically when
	 * the value set by setProgress is >= max, but it may be called earlier if
	 * the operation ends early.
	 */
	public void close() {
		fileProgressBar = null;
	}

	/**
	 * Returns the maximum value -- the higher end of the progress value.
	 * 
	 * @return an int representing the maximum value
	 * @see #setMaximum
	 */
	public int getMaximum() {
		return max;
	}

	/**
	 * Specifies the maximum value.
	 * 
	 * @param m
	 *            an int specifying the maximum value
	 * @see #getMaximum
	 */
	public void setMaximum(int m) {
		if (fileProgressBar != null) {
			fileProgressBar.setMaximum(m);
		}
		max = m;
	}

}
